package cn.wenlihelp.controller.power;

import cn.wenlihelp.bean.Resources;
import cn.wenlihelp.bean.Role;
import cn.wenlihelp.model.Result;
import cn.wenlihelp.model.TreeItem;
import cn.wenlihelp.service.ResourcesService;
import cn.wenlihelp.service.RoleService;
import com.github.pagehelper.PageInfo;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/role")
public class RoleController {

    private int errorCodeRoot = 30000;

    private String model = "role";
    private String modelPath = "power/" + model;
    @Resource
    private RoleService roleService;
    @Resource
    private ResourcesService resourcesService;
    @RequestMapping
    public ModelAndView home() {
        return new ModelAndView(modelPath + "/index");
    }

    @GetMapping("/add")
    public ModelAndView addPage() {
        return new ModelAndView(modelPath + "/add");
    }

    @GetMapping("/resource/{id}")
    public ModelAndView resourceMapping(@PathVariable("id")Integer roleId, ModelMap modelMap) {
        Role role = roleService.findById(roleId.longValue());
        modelMap.addAttribute(model, role);
        return new ModelAndView(modelPath +"/resourceMapping");
    }
    //关联资源的方法
    @PostMapping("/resource/{id}")
    public Result resourceMapping(@PathVariable("id") Integer roleId,@RequestParam(name = "resourceIds[]",required = false) Integer[] resourceIds) {
        try {

            this.roleService.resourceMapping(roleId,resourceIds);
            return Result.success("关联成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result<>().setCode(this.errorCodeRoot+4).setMsg("关联失败");
    }
    @GetMapping("/resource")
    public Result<TreeItem> findResources(Integer roleId){
        //查询已关联的资源
        List<Resources> resourcesList = resourcesService.findByRoleId(roleId);
        //将关联的资源对象列表转换为资源ID列表
        Set<Integer> resourceIds = resourcesList.stream().map(Resources::getId).collect(Collectors.toSet());

        List<Resources> resources = resourcesService.findAll(null);
        List<TreeItem> treeItems = new ArrayList<>();
        Map<Integer, TreeItem> treeItemMap = new HashMap<>();
        //第一次循环，将所有resource转换成TreeItem
        for (Resources resource: resources) {
            TreeItem treeItem = new TreeItem(resource);

            treeItemMap.put(treeItem.getId(),treeItem);
            //如果当前的资源对象没有父资源，则放入集合
            if(resource.getPid() == -1) {
                treeItems.add(treeItem);
                treeItem.setSpread(true);
            }
        }
        //第二次循环，处理所有的TreeItem关系
        for (Resources resource: resources) {
            //如果当前的资源对象没有父资源，则放入集合
            if(resource.getPid() != -1) {
                TreeItem treeItem = treeItemMap.get(resource.getPid());
                treeItem.getChildren().add(treeItemMap.get(resource.getId()));
            }
        }

        for (Resources resource: resources) {
            TreeItem treeItem = treeItemMap.get(resource.getId());
            if(treeItem.getChildren().isEmpty()){
                treeItem.setChecked(resourceIds.contains(treeItem.getId()));
            }
        }

        return Result.success(treeItems);
    }
    @GetMapping("/{id}")
    public ModelAndView updatePage(@PathVariable("id") Long id, ModelMap modelMap) {
        Role role = roleService.findById(id);
        modelMap.addAttribute(model, role);
        return new ModelAndView(modelPath + "/update");
    }

    //region 查询角色
    @GetMapping(produces = "application/json")
    public Object findAll(Role role,
                          @RequestParam(defaultValue = "1") int page,
                          @RequestParam(defaultValue = "10") int limit) {
        PageInfo<Role> pageInfo = roleService.findAll(page, limit, role);
        return Result.success(pageInfo.getTotal(), pageInfo.getList());
    }
    //endregion

    //region 批量删除角色
    @DeleteMapping
    public Result deleteByIds(@RequestParam("ids[]") Integer[] ids) {
        if (roleService.deleteByIds(ids)) {
            return Result.success("删除成功");
        } else {
            return new Result().setCode(errorCodeRoot + 1).setMsg("删除失败");
        }
    }
    //endregion

    //region 新增角色
    @PutMapping
    public Result add(@RequestBody Role role) {
        if (roleService.insert(role)) {
            return Result.success("新增成功");
        } else {
            return new Result().setCode(errorCodeRoot + 2).setMsg("新增失败");
        }
    }
    //endregion


    //region 修改角色
    @PostMapping
    public Result updataRole(@RequestBody Role role) {
        if (roleService.updateByPrimaryKey(role)) {
            return Result.success("修改成功");
        } else {
            return new Result().setCode(errorCodeRoot + 3).setMsg("新增失败");
        }
    }
    //endregion


}
